package eu.codlab.twitteirb;

import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class CookieManager {
	HashMap<String,String> _map;
	public CookieManager(){
		_map = new HashMap<String,String>();


	}
	public void storeCookies(String cookie){
		//Log.d("storeCookies",cookie);
		String[] _split = cookie.split(";");
		for(int i=0;i<_split.length && i==0;i++){
			String [] c = _split[i].split("=");
			while(c[0].indexOf(" ") == 0)
				c[0]=c[0].substring(1, c[0].length());
			while(c[0].lastIndexOf(" ") == c[0].length())
				c[0]=c[0].substring(0, c[0].length()-1);
			//Log.d("storeCookies store",c[0]+" "+(c.length>1 ? c[1] : ""));

			_map.put(c[0], c.length>1 ? c[1] : "");
		}
	}

	public void setCookies(URLConnection c){
		String r = "";
		String sep="";
		Iterator<String> set = _map.keySet().iterator();
		while(set.hasNext()){
			String name = set.next();
			r+=sep;
			r+=name;
			r+="=";
			r+=_map.get(name);
			sep=";";
		}
		//Log.d("set Cookie",r);
		c.setRequestProperty("Cookie", r);
	}

	public String getCookie(String n){
		Set<String> key = _map.keySet();
		Iterator<String> it = key.iterator();
		String res = "";
		String sep="";
		while(it.hasNext()){
			String k = it.next();
			if(k!=null && k.equals(n)){
				res=k;
				res+="=";
				res+=_map.get(k);
				return res;
			}//else
				//Log.d("k", k+" "+n);
		}
		return res;
	}
	public String getCookie(){
		Set<String> key = _map.keySet();
		Iterator<String> it = key.iterator();
		String res = "";
		String sep="";
		while(it.hasNext()){
			String k = it.next();
			res+=sep;
			res+=k;
			res+="=";
			res+=_map.get(k);
			sep=";";
		}
		return res;
	}
	public String toString(){
		return getCookie();
	}


}
